package edu.tjpu.share.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import edu.tjpu.share.service.UploadService;

public class FileUploadClient {
	private String HOST = null;
	private int PORT = 0;
	private Socket socket = null;
	FileInputStream fis = null;
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;

	public FileUploadClient(String HOST, int PORT) {
		this.HOST = HOST;
		this.PORT = PORT;
	}

	public boolean doUpload(String FileInUrl,String fileName, Handler uploadHandler,int notification_id) {
		int count = 0;
		int totalSize=0;
		if (FileInUrl != null && HOST != null && PORT != 0) {
			File fileIn = new File(FileInUrl);
			try {
				fis = new FileInputStream(fileIn);
				bis = new BufferedInputStream(fis);
				socket = new Socket(HOST, PORT);
				bos = new BufferedOutputStream(socket.getOutputStream());
				totalSize = Long.valueOf(fileIn.length()).intValue();
				//pd.setMax(totalSize);
				int ch = -1;
				int uploadPercent = 0;
				while ((ch = bis.read()) != -1) {
					bos.write(ch);
					count++;
					//pd.setProgress(count);
					if (((100*count / totalSize) - 1) > uploadPercent) {
						uploadPercent++;
						Message msg = new Message();
						Bundle bundle = new Bundle();
						bundle.putString("fileName", fileName);
						bundle.putInt("notification_id", notification_id);
						bundle.putInt("uploadPercent", uploadPercent);
						msg.what=UploadService.UPDATE_UPLOAD;
						msg.setData(bundle);
						uploadHandler.sendMessage(msg);
					}
				}
				bos.flush();
				//pd.cancel();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					bos.close();
					bis.close();
					socket.close();
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return count==totalSize;

	}

}
